#!/bin/sh
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-populate-root.sh
# author: david921518@qq.com

let COUNTER=0
WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
while [ "${WAN_IP}"x == x ]; do
  sleep 1
  let COUNTER=$COUNTER+1
  if [ $COUNTER -gt 29 ]; then
    echo "Can't get WAN IP address, reboot now" 2>&1 | tee /dev/kmsg
    while true; do reboot; sleep 9; done
  fi
  WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
done

echo "[populate-root] WAN IP=[${WAN_IP}]" 2>&1 | tee /dev/kmsg
sleep 1
echo "[populate-root] PATH=[$PATH]" 2>&1 | tee /dev/kmsg
sleep 1

# 1. banner
if [ -f /root/firstboot/root/etc/banner ]; then
  cp -f /root/firstboot/root/etc/banner /etc/banner
fi

# 2. bind
if [ -e /root/firstboot/root/etc/bind ]; then
  cp -af /root/firstboot/root/etc/bind/* /etc/bind/
fi

# 3. board.d
if [ -e /root/firstboot/root/etc/board.d ]; then
  cp -af /root/firstboot/root/etc/board.d/* /etc/board.d/
fi

# 4. init.d
if [ -e /root/firstboot/root/etc/init.d ]; then
  cp -af /root/firstboot/root/etc/init.d/* /etc/init.d/
fi

# 5. rc.d
if [ -e /root/firstboot/root/etc/rc.d ]; then
  cp -af /root/firstboot/root/etc/rc.d/* /etc/rc.d/
fi

# 6. /usr/sbin
if [ -e /root/firstboot/root/usr/sbin ]; then
  cp -af /root/firstboot/root/usr/sbin/* /usr/sbin/
fi

sync
sleep 1

echo "[populate-root] EXIT" 2>&1 | tee /dev/kmsg
sleep 1

# restart system
#poweroff

